#!/bin/bash
#
# This script is for starting and stopping the haikudepotserver${rpm.variant} service.
#
# chkconfig: 345 80 20
#
### BEGIN INIT INFO
# Provides: haikudepotserver${rpm.variant}
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:
# Default-Stop:
# Description: Haiku Depot Server
# Short-Description: start and stop haikudepotserver${rpm.variant}
### END INIT INFO

HDS_CONFIGBASE=/etc/haikudepotserver${rpm.variant}
HDS_HOME=/opt/haikudepotserver${rpm.variant}
HDS_LOGFILE=/var/log/haikudepotserver${rpm.variant}/haikudepotserver${rpm.variant}.log
HDS_PSIDENTIFIER=haikudepotserver${rpm.variant}-3D84A80C-38A4-40BC-9AEE-86C3CA986517

MAXSHUTDOWNDELAYSECONDS=20

JAVA_HOME=/usr/lib/jvm/jre
JAVA_OPTS="-Dfile.encoding=UTF-8 \
-Dlogback.configurationFile=${HDS_CONFIGBASE}/logback.xml \
-Duser.timezone=GMT0 \
-Xms512m -Xmx640m \
-Djava.awt.headless=true \
-Dconfig.properties=file://${HDS_CONFIGBASE}/config.properties \
-jar ${HDS_HOME}/haikudepotserver-webapp-exec-war.jar \
-resetExtract \
-httpPort ${rpm.http.port} \
-extractDirectory /var/cache/haikudepotserver${rpm.variant}/extract"

haikudepotserver_pid() {
  echo `ps aux | grep "${HDS_PSIDENTIFIER}" | grep -v grep | awk '{ print $2 }'`
}

start() {
  pid="$(haikudepotserver_pid)"
  if [ -n "$pid" ]; then
    echo "haikudepotserver${rpm.variant}; is already running (pid: $pid)"
  else
    echo "haikudepotserver${rpm.variant}; starting..."
    /bin/su -s /bin/bash haikudepotserver${rpm.variant} -c "${JAVA_HOME}/bin/java ${JAVA_OPTS} -Dcommand.identifier=${HDS_PSIDENTIFIER} 2>&1 | tee -a ${HDS_LOGFILE} > /dev/null &"
  fi
  return 0
}

stop() {
 pid="$(haikudepotserver_pid)"
  if [ -n "$pid" ]; then
    echo "haikudepotserver${rpm.variant}; stopping... (pid: $pid)"
    kill "$pid"

    count=0;
    while [[ -n "$(haikudepotserver_pid)" && ("$count" -lt "${MAXSHUTDOWNDELAYSECONDS}") ]]; do
        sleep 1
        let count+=1
    done;

    if [[ -n "$(haikudepotserver_pid)" ]]; then
        echo "haikudepotserver${rpm.variant}; unable to be stopped"
    else
        echo "haikudepotserver${rpm.variant}; stopped"
    fi
  else
    echo "haikudepotserver${rpm.variant}; not running"
  fi
  return 0
}

case $1 in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  status)
    pid="$(haikudepotserver_pid)"
    if [ -n "$pid" ]; then
      echo "haikudepotserver${rpm.variant}; running (pid: $pid)"
    else
      echo "haikudepotserver; not running"
    fi
    ;;
esac

exit 0